import os.path
from menu import main_menu
import re

fileName = "student.txt"
def insert():
    studentList = []
    mark = True
    while mark:
        id = input("请输入ID(如 1001): ")
        if not id: # ID 为空
            break
        name = input("请输入名称: ")

        if not name:
            break

        try:
            english = int(input("请输入英语成绩: "))
            python = int(input("请输入Python成绩: "))
            c = int(input("请输入C语言成绩: "))
        except Exception as e:
            print("输入成绩无效，不是整数...重新录入信息: ")
            continue
        stdent = {"id": id, "name": name, "english": english, "python": python, "c": c}

        studentList.append(stdent)

        #inputMark = input("是否继续添加?(y/n): ")
        mark = inputTip("是否继续添加?")


        save(studentList)

def search():
    mark = True
    student_query = []
    while mark:
        id = ""
        name = ""
        if not os.path.exists(fileName):
            print("暂未保存数据信息...")
            return

        mode = input("按ID查询输入1;按照姓名查询输入2: ")
        if mode == "1":
            id = input("请输入学生ID: ")
        elif mode == "2":
            name = input("请输入学生名称: ")
        else:
            print("您输入的有错误，请重新输入:")
            search()

        with open(fileName, 'r') as file:
            students = file.readlines()
            for list in students:
                d = dict(eval(list)) # 字符串转字典
                if id != "":
                    if d["id"] == id:
                        student_query.append(d)
                elif name != "":
                    if d["name"] == name:
                        student_query.append(d)
        show_student(student_query)
        student_query.clear()

        mark = inputTip("是否继续查询")

def inputTip(tip):
    inputMark = input(tip + "(y/n): ")
    if inputMark == "y":
        return True
    else:
        return False
def show_student(students):
    if not students:
        print("(O@.@O)无数据信息(O@.@O)\n")
        return

    format_title = "{:^6}\t{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
    print(format_title.format("ID", "名字", "英语成绩", "Python成绩", "C语言成绩", "总成绩"))

    format_data = "{:^6}\t{:^12}\t{:^12}\t{:^12}\t{:^12}\t{:^12}"
    for info in students:
        sum = str(int(info.get("english")) + int(info.get("python")) + int(info.get("c"))).center(12)
        print(format_data.format(info.get("id"),info.get("name"),info.get("english"),info.get("python"),info.get("c"),sum))


def delete():
    mark = True
    while mark:
        studentId = input("请输入要删除学生的ID: ")
        if studentId == "":
            return
        if os.path.exists(fileName):
            with open(fileName, 'r') as rfile:
                student_old = rfile.readlines()
        else:
            student_old = []
        ifdel = False;

        if not student_old:
            print("无学生信息...")
            break
        else:
            with open(fileName, 'w') as wfile:
                d = {}
                for list in student_old:
                    d = dict(eval(list))
                    if d['id'] != studentId:
                        wfile.write(str(d) + "\n")
                    else:
                        ifdel = True
                if ifdel:
                    print("ID为%s的学生信息已经被删除..." %studentId)
                else:
                    print("没有找到ID为%s的学生信息..." %studentId)
        show()
        mark = inputTip("是否继续删除?")

def modify():
    show()
    if os.path.exists(fileName):
        with open(fileName,'r') as rfile:
            student_old = rfile.readlines()
    else:
        return
    studentId = input("请输入你要修改学生的ID: ")
    with open(fileName, 'w') as wfile:
        for student in student_old:
            d = dict(eval(student))
            if d['id'] == studentId:
                print("找到了这名学生，可以修改他的信息:")
                while True:
                    try:
                        d['name'] = input("请输入姓名: ")
                        d['english'] = int(input("请输入英语成绩: "))
                        d['python'] = int(input("请输入Python成绩: "))
                        d['c'] = int(input("请输入c成绩: "))
                    except Exception as e:
                        print("您输入的有误，请重新输入:")
                    else:
                        break
                student = str(d)
                print("修改后的信息如下:")
                print(student)
                wfile.write(student + "\n")
            else:
                wfile.write(student)
        mark = inputTip("是否继续修其他学生信息?")
        if mark:
            modify()


def sort():
    show()
    if os.path.exists(fileName):
        with open(fileName, 'r') as rfile:
            student_old = rfile.readlines()
            student_new = []
        for list in student_old:
            d = dict(eval(list))
            student_new.append(d)
    else:
        return
    ascORdesc = input("请选择(0 升序;1 降序): ")
    if ascORdesc == '0':
        ascORdescBool = False
    elif ascORdesc == '1':
        ascORdescBool = True
    else:
        print("输入有误，请重新输入:")
        sort()
    mode = input("请选择排序方式(1 按照英语成绩排序;2 按照python成绩排序;3 按照C语言成绩排序: 0 按照总成绩排序): ")
    if mode == '1':
        student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool)
    elif mode == '2':
        student_new.sort(key=lambda x: x['python'], reverse=ascORdescBool)
    elif mode == '3':
        student_new.sort(key=lambda x: x['c'], reverse=ascORdescBool)
    elif mode == '0':
        student_new.sort(key=lambda x: x['english'] + x['python'] + x['c'], reverse=ascORdescBool)
    else:
        print("输入有误，请重新输入!")
        sort()
    show_student(student_new)

def total():
    if os.path.exists(fileName):
        with open(fileName, 'r') as rfile:
            student_old = rfile.readlines()
        if student_old:
            print("一共有%d名学生" %len(student_old))
        else:
            print("还没有录入学生！")
    else:
        print("暂未保存数据信息...")

def show():
    student_new = []
    if not os.path.exists(fileName):
        print("暂未保持数据信息")
    else:
        with open(fileName, 'r') as rfile:
            student_old = rfile.readlines()
        for list in student_old:
            student_new.append(eval(list))
        if student_new:
            show_student(student_new)


def save(students):
    try:
        students_txt = open(fileName,"a")
    except Exception as e:
        students_txt = open(fileName, "w") # 文件不存在，创建文件并打开
    for info in students:
        students_txt.write(str(info) + "\n")
    students_txt.close()


def main():
    ctrl = True
    while(ctrl):
        main_menu.menu()
        option = input("请选择: ")
        option_str = re.sub("\D","",option) # 提取数字
        if option_str in ['0','1','2','3','4','5','6','7']:
            option_int = int(option_str)
            if option_int == 0:
                print("您已经推出学生信息管理系统")
                ctrl = False
            elif option_int == 1:
                insert()
            elif option_int == 2:
                search()
            elif option_int == 3:
                delete()
            elif option_int == 4:
                modify()
            elif option_int == 5:
                sort()
            elif option_int == 6:
                total()
            elif option_int == 7:
                show()

if __name__ == "__main__":
    main()